<template>
  <div class="flex h-screen bg-[#f5f7fa]">
    <!-- 左侧菜单 -->
    <Sidebar />

    <!-- 右侧内容区 -->
    <div class="flex flex-1 flex-col overflow-hidden">
      <!-- 顶部导航栏 -->
      <div class="flex h-16 items-center justify-between bg-white px-4 shadow">
        <!-- 面包屑 -->
        <el-breadcrumb>
          <el-breadcrumb-item :to="{ path: '/teacher' }"
            >教师端</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ currentRoute.meta.title }}</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 用户信息 -->
        <div class="flex items-center space-x-4">
          <el-dropdown @command="handleCommand">
            <span class="flex cursor-pointer items-center">
              <el-avatar :size="40" :src="userAvatar" />
              <span class="ml-2">{{ userName }}</span>
              <el-icon class="ml-1"><CaretBottom /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="logout" divided
                  >退出登录</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 标签页 -->
      <div class="bg-white px-2 border-0">
        <el-tabs
          v-model="activeTab"
          type="card"
          closable
          @tab-click="handleTabClick"
          @tab-remove="handleTabRemove"
          class="custom-tabs"
        >
          <el-tab-pane
            v-for="tab in visitedViews"
            :key="tab.path"
            :label="tab.title"
            :name="tab.path"
            :closable="tab.path !== '/teacher/home'"
          />
        </el-tabs>
      </div>

      <!-- 主要内容区 -->
      <div class="flex-1 overflow-auto p-4">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTagsStore } from '@/store/modules/tags'
import { useUserStore } from '@/store/modules/user'
import Sidebar from './views/components/Sidebar.vue'
import Sortable from 'sortablejs'
import { debounce } from 'lodash-es'

const route = useRoute()
const router = useRouter()
const tagsStore = useTagsStore()
const userStore = useUserStore()

// sortable实例
let sortable = null

// 用户信息
const userAvatar = computed(
  () =>
    userStore.userInfo?.avatar ||
    'https://api.dicebear.com/7.x/avataaars/svg?seed=student'
)
const userName = computed(() => userStore.userInfo?.name || '')

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 当前路由信息
const currentRoute = computed(() => route)

// 访问过的页面标签
const visitedViews = computed(() => tagsStore.visitedViews)
const cachedViews = computed(() => tagsStore.cachedViews)
const activeTab = computed({
  get: () => route.path,
  set: (val) => {
    router.push(val)
  },
})

// 处理标签页点击
const handleTabClick = (tab) => {
  router.push(tab.props.name)
}

// 处理标签页关闭
const handleTabRemove = (targetPath) => {
  tagsStore.delView(targetPath)
  if (activeTab.value === targetPath) {
    const lastView = visitedViews.value.slice(-1)[0]
    if (lastView) {
      router.push(lastView.path)
    } else {
      router.push('/teacher/home')
    }
  }
}

// 处理用户下拉菜单
const handleCommand = async (command) => {
  if (command === 'profile') {
    router.push('/teacher/userInfo')
  } else if (command === 'logout') {
    await userStore.logOut()
    router.push('/login')
  }
}


// 添加路由监听来处理标签页
watch(
  () => route.path,
  () => {
    const { name, path, meta } = route
    if (path.startsWith('/teacher')) {
      tagsStore.addView({
        name,
        path,
        meta,
      })
    }
  },
  { immediate: true } // 确保首次加载时也能添加标签页
)

// 使用防抖优化初始化
const initSortable = () => {
  try {
    const el = document.querySelector('.el-tabs__nav')
    if (!el) return

    // 销毁之前的sortable实例，避免重复绑定
    if (sortable) {
      sortable.destroy()
    }

    // 创建新的sortable实例
    sortable = Sortable.create(el, {
      animation: 300,
      delay: 0, // 延迟拖拽，单位毫秒
      handle: '.el-tabs__item', // 拖拽的触发元素
      filter: '.is-disabled', // 不允许拖拽的选择器
      draggable: '.el-tabs__item', // 可以被拖拽的元素
      preventOnFilter: false,
      ghostClass: 'ghost', // 拖拽过程中元素的类名
      chosenClass: 'chosen', // 选中元素的类名
      onStart: (evt) => {
        console.log('拖拽开始', evt.oldIndex)
      },
      onEnd: (evt) => {
        if (evt.oldIndex !== evt.newIndex) {
          // 拖拽结束，更新store中的标签顺序
          tagsStore.moveTag(evt.oldIndex, evt.newIndex)
          // 同步更新缓存视图的顺序
          tagsStore.updateCachedViewsOrder()
        }
      },
    })
  } catch (error) {
    console.error('初始化拖拽功能失败:', error)
  }
}

// 使用防抖减少频繁初始化
const debouncedInitSortable = debounce(initSortable, 200)

// 监听标签列表变化，重新初始化sortable
watch(() => visitedViews.value.length, debouncedInitSortable)

// 组件挂载后初始化sortable
onMounted(() => {
  nextTick(() => {
    initSortable()
  })
})
</script>

<style scoped>
:deep(.el-menu) {
  border-right: none;
}

:deep(.el-tabs__item) {
  margin-right: 6px !important;
}

:deep(.el-tabs--card > .el-tabs__header) {
  border-bottom: none;
  margin: 0;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
  border: none;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  border: 1px solid #dcdfe6;
  border-radius: 4px 4px 0 0;
  margin: 0 2px -1px 0;
  height: 32px;
  line-height: 32px;
  background-color: #f5f7fa;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  background-color: #fff;
  border-bottom-color: #fff;
  color: var(--el-color-primary);
}

:deep(.el-tabs__nav-wrap) {
  position: relative;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.no-shadow) {
  box-shadow: none !important;
}

:deep(.el-tabs__header) {
  box-shadow: none !important;
  border-bottom: none !important;
}

:deep(.el-tabs__content) {
  box-shadow: none !important;
}

/* 修改自定义标签页样式 */
:deep(.custom-tabs) {
  .el-tabs__header {
    margin: 0;
    border: none;
    padding: 5px 0;
  }

  .el-tabs__nav {
    border: none !important;
    height: 32px;
  }

  .el-tabs__item {
    height: 32px !important;
    line-height: 32px !important;
    background: #fff !important;
    border: 1px solid #dcdfe6 !important;
    padding: 0 15px !important;
    color: #666 !important;
    margin: 0 4px !important;
    transition: all 0.3s;
    border-radius: 3px !important;
    cursor: pointer;
    user-select: none;
  }

  .el-tabs__item.is-active {
    background: var(--el-color-primary) !important;
    color: #fff !important;
    border-color: var(--el-color-primary) !important;
  }

  .el-tabs__item:not(.is-active):hover {
    color: var(--el-color-primary) !important;
    border-color: var(--el-color-primary) !important;
  }

  .el-icon-close {
    color: inherit;
    font-size: 12px;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    margin-left: 4px;
  }
}

/* 拖拽相关样式 */
.ghost {
  opacity: 0.6;
  background: var(--el-color-primary-light-9) !important;
  border: 1px dashed var(--el-color-primary) !important;
}

.chosen {
  background: var(--el-color-primary-light-8) !important;
}

/* 动画效果 */
.sortable-drag {
  opacity: 0.8;
  background: var(--el-color-primary-light-9) !important;
  border: 1px dashed var(--el-color-primary) !important;
  z-index: 9999;
}

/* 确保移除底部边框线 */
:deep(.el-tabs__nav-wrap)::after {
  display: none !important;
}

/* 路由过渡动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 移除下拉菜单hover边框 */
:deep(.el-dropdown) {
  outline: none;
}

:deep(.el-dropdown:focus-visible) {
  outline: none;
}

:deep(.el-dropdown:hover) {
  border-color: transparent;
}

:deep(.el-dropdown:focus) {
  border-color: transparent;
}

:deep(.el-dropdown .el-dropdown__default-focus-trap) {
  border: none !important;
  outline: none !important;
}

:deep(.el-dropdown .el-focus-trap) {
  border: none !important;
  outline: none !important;
}
</style>
